package com.ibeeking.gmc.global.g.rest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ibeeking.found.common.entity.ShortUrlDTO;
import com.ibeeking.found.common.entity.ShortUrlQueryFeign;
import com.ibeeking.gmc.global.g.rest.service.IShortUrlService;
import com.ibeeking.gmc.global.service.common.dos.ShortUrlDO;
import com.ibeeking.gmc.global.service.common.param.ShortUrlParam;
import com.ibeeking.gmc.global.service.common.query.ShortUrlPageQuery;
import com.ibeeking.gmc.global.service.common.query.ShortUrlQuery;
import com.ibeeking.gmc.global.service.common.vo.ShortUrlVO;
import com.ibeeking.gmc.global.service.mapper.ShortUrlMapper;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.date.DateUtil;
import com.ibeeking.nematos.utils.json.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ShortUrlServiceImpl extends ServiceImpl<ShortUrlMapper, ShortUrlDO> implements IShortUrlService {
    @Resource
    private ShortUrlMapper ShortUrlMapper;

    /**
     * 条件查询
     *
     * @param query
     * @return
     */
    @Override
    public List<ShortUrlVO> list(ShortUrlQuery query){
        List<ShortUrlVO> resukltVOS = Collections3.emptyList();
        List<ShortUrlDO> entityDOS = this.ShortUrlMapper.selectList(new LambdaQueryWrapper<ShortUrlDO>()
                .eq(query.getId() != null, ShortUrlDO::getId, query.getId())
                .eq(query.getTenantId() != null, ShortUrlDO::getTenantId, query.getTenantId())
                .eq(query.getPageType() != null, ShortUrlDO::getPageType, query.getPageType())
                .eq(StringUtils.isNotEmpty(query.getPageId()), ShortUrlDO::getPageId, query.getPageId())
                .like(StringUtils.isNotEmpty(query.getPageName()), ShortUrlDO::getPageName, query.getPageName())
                .eq(StringUtils.isNotEmpty(query.getShorterKey()), ShortUrlDO::getShorterKey, query.getShorterKey())
                .ge(StringUtils.isNotEmpty(query.getExpireTimeBegin()), ShortUrlDO::getExpireTime, query.getExpireTimeBegin())
                .le(StringUtils.isNotEmpty(query.getExpireTimeEnd()), ShortUrlDO::getExpireTime, query.getExpireTimeEnd())
        );
        if(Collections3.isNotEmpty(entityDOS)){
            resukltVOS = entityDOS.stream().map(d->{
                ShortUrlVO entityVO = BeanUtil.convertBean(d, ShortUrlVO.class);
                Integer hasExpired= d.getHasExpired();
                if(hasExpired==1){
                    entityVO.setExpireTime("长期有效");
                }else{
                    entityVO.setExpireTime(DateUtil.localDateTimeToStr(d.getExpireTime()));
                }
                if(d.getCreateTime() !=null){
                    entityVO.setCreateTime(DateUtil.localDateTimeToStr(d.getCreateTime()));
                }
                return entityVO;
            }).collect(Collectors.toList());
        }
        return resukltVOS;
    }
    /**
     * 条件查询
     *
     * @param tenantId
     * @return
     */
    @Override
    public List<ShortUrlDTO> queryListByTenantId(Integer tenantId){
        List<ShortUrlDO> entityDOS = this.ShortUrlMapper.selectList(new LambdaQueryWrapper<ShortUrlDO>()
                .eq(ShortUrlDO::getTenantId, tenantId)
        );
        return JsonUtils.jsonToList(entityDOS, ShortUrlDTO.class);
    }
    /**
     * 条件查询
     *
     * @param query
     * @return
     */
    @Override
    public List<ShortUrlDTO> queryShortUrlList(ShortUrlQueryFeign query){
        List<ShortUrlDO> entityDOS = this.ShortUrlMapper.selectList(new LambdaQueryWrapper<ShortUrlDO>()
                .eq(query.getTenantId() != null, ShortUrlDO::getTenantId, query.getTenantId())
                .eq(query.getPageType() != null, ShortUrlDO::getPageType, query.getPageType())
                .eq(StringUtils.isNotEmpty(query.getPageId()), ShortUrlDO::getPageId, query.getPageId())
                .eq(StringUtils.isNotEmpty(query.getShorterKey()), ShortUrlDO::getShorterKey, query.getShorterKey())
                .ge(StringUtils.isNotEmpty(query.getExpireTimeBegin()), ShortUrlDO::getExpireTime, query.getExpireTimeBegin())
                .le(StringUtils.isNotEmpty(query.getExpireTimeEnd()), ShortUrlDO::getExpireTime, query.getExpireTimeEnd())
        );
        return JsonUtils.jsonToList(entityDOS, ShortUrlDTO.class);
    }

    /**
     * 分页条件查询
     *
     * @param pageQuery
     * @return
     */
    @Override
    public Page<ShortUrlVO> pageList(ShortUrlPageQuery pageQuery) {
        LambdaQueryWrapper<ShortUrlDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(pageQuery.getId() != null, ShortUrlDO::getId, pageQuery.getId())
                .eq(pageQuery.getTenantId() != null, ShortUrlDO::getTenantId, pageQuery.getTenantId())
                .eq(pageQuery.getPageType() != null, ShortUrlDO::getPageType, pageQuery.getPageType())
                .eq(StringUtils.isNotEmpty(pageQuery.getPageId()), ShortUrlDO::getPageId, pageQuery.getPageId())
                .like(StringUtils.isNotEmpty(pageQuery.getPageName()), ShortUrlDO::getPageName, pageQuery.getPageName())
                .eq(StringUtils.isNotEmpty(pageQuery.getShorterKey()), ShortUrlDO::getShorterKey, pageQuery.getShorterKey())
                .ge(StringUtils.isNotEmpty(pageQuery.getExpireTimeBegin()), ShortUrlDO::getExpireTime, pageQuery.getExpireTimeBegin())
                .le(StringUtils.isNotEmpty(pageQuery.getExpireTimeEnd()), ShortUrlDO::getExpireTime, pageQuery.getExpireTimeEnd())
                .orderByAsc(ShortUrlDO::getTenantId);
        Page<ShortUrlDO> dOPages = ShortUrlMapper.selectPage(new Page<ShortUrlDO>(pageQuery.getPageNum(), pageQuery.getPageSize()), wrapper);
        Page<ShortUrlVO> vOPage = BeanUtil.convertPage(dOPages, ShortUrlVO.class);
        if(vOPage!=null && vOPage.getSize()>0){
            vOPage.getRecords().stream().forEach(d->{
                Integer hasExpired= d.getHasExpired();
                if(hasExpired==1){
                    d.setExpireTime("长期有效");
                }
            });
        }
        return vOPage;
    }


    /**
     * 根据id查看详情
     *
     * @param id
     * @return
     */
    @Override
    public ShortUrlVO view(Long id) {
        ShortUrlDO entityDO = this.ShortUrlMapper.selectById(id);
        ShortUrlVO entityVO = BeanUtil.convertBean(entityDO, ShortUrlVO.class);
        return entityVO;
    }

    /**
     * 根据id查看详情
     *
     * @param shorterKey
     * @return
     */
    @Override
    public ShortUrlDTO queryByShorterKey(Integer tenantId, String shorterKey) {
        ShortUrlDO entityDO = this.ShortUrlMapper.selectOne(new LambdaQueryWrapper<ShortUrlDO>()
                .eq(tenantId != null, ShortUrlDO::getTenantId, tenantId)
                .eq(StringUtils.isNotEmpty(shorterKey), ShortUrlDO::getShorterKey, shorterKey)
        );
        ShortUrlDTO entityDTO = BeanUtil.convertBean(entityDO, ShortUrlDTO.class);
        return entityDTO;
    }

    /**
     * 根据id查看详情
     *
     * @param query
     * @return
     */
    @Override
    public ShortUrlDTO queryShortUrlOne(ShortUrlQueryFeign query) {
        ShortUrlDO entityDO = this.ShortUrlMapper.selectOne(new LambdaQueryWrapper<ShortUrlDO>()
                .eq(query.getTenantId() != null, ShortUrlDO::getTenantId, query.getTenantId())
                .eq(query.getPageType() != null, ShortUrlDO::getPageType, query.getPageType())
                .eq(StringUtils.isNotEmpty(query.getPageId()), ShortUrlDO::getPageId, query.getPageId())
                .eq(StringUtils.isNotEmpty(query.getShorterKey()), ShortUrlDO::getShorterKey, query.getShorterKey())
                .ge(StringUtils.isNotEmpty(query.getExpireTimeBegin()), ShortUrlDO::getExpireTime, query.getExpireTimeBegin())
                .le(StringUtils.isNotEmpty(query.getExpireTimeEnd()), ShortUrlDO::getExpireTime, query.getExpireTimeEnd())
        );
        return BeanUtil.convertBean(entityDO, ShortUrlDTO.class);
    }

    /**
     * 添加
     *
     * @param param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(ShortUrlParam param) {
        this.checkShortUrl(param);
        ShortUrlDO entityDO = BeanUtil.convertBean(param, ShortUrlDO.class);
        Integer hasExpired= param.getHasExpired();
        if(hasExpired==1){
            entityDO.setExpireTime(null);
            entityDO.setHasExpired(1);
        }else{
            String expireDate = param.getExpireTime();
            if(StringUtils.isNotEmpty(expireDate)){
                LocalDateTime expireDateTime = DateUtil.strToLocalDateTime(expireDate);
                entityDO.setExpireTime(expireDateTime);
                entityDO.setHasExpired(2);
            }
        }
        entityDO.setCreateTime(LocalDateTime.now());
        entityDO.setModifyTime(LocalDateTime.now());
        return this.ShortUrlMapper.insert(entityDO) > 0;
    }


    /**
     * 修改
     *
     * @param param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean modify(ShortUrlParam param) {
        ShortUrlDO entityDO = BeanUtil.convertBean(param, ShortUrlDO.class);
        Integer hasExpired= param.getHasExpired();
        if(hasExpired==1){
            entityDO.setExpireTime(null);
            entityDO.setHasExpired(1);
        }else{
            String expireDate = param.getExpireTime();
            if(StringUtils.isNotEmpty(expireDate)){
                LocalDateTime expireDateTime = DateUtil.strToLocalDateTime(expireDate);
                entityDO.setExpireTime(expireDateTime);
                entityDO.setHasExpired(2);
            }
        }
        entityDO.setModifyTime(LocalDateTime.now());
        return this.ShortUrlMapper.updateById(entityDO) > 0;
    }

    /**
     * 根据id删除集团
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean del(Long id) {
        ShortUrlDO entityDO = this.ShortUrlMapper.selectById(id);
        if (entityDO == null) {
            throw new BusinessException("数据不存在");
        }
        return this.ShortUrlMapper.deleteById(id) > 0;
    }

    /**
     * 检查是否有重复
     *
     * @param param
     */
    private void checkShortUrl(ShortUrlParam param) {
        QueryWrapper<ShortUrlDO> quary = new QueryWrapper<>();
        quary.lambda().eq(ShortUrlDO::getTenantId, param.getTenantId())
                .eq(ShortUrlDO::getShorterKey, param.getShorterKey())
                .ne(param.getId() != null, ShortUrlDO::getId, param.getId());
        List<ShortUrlDO> ShortUrlList = this.ShortUrlMapper.selectList(quary);
        if (Collections3.isNotEmpty(ShortUrlList)) {
            throw new BusinessException("数据已经存在");
        }
    }


}
